package com.sky.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.RedisKeyConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.service.IDishFlavorService;
import com.sky.service.IDishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品相关接口
 *
 * @Author mr.Du
 * @Date 2025/5/21 2025/5/21
 */
@Service
public class IDishServiceImpl extends ServiceImpl<DishMapper, Dish> implements IDishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private IDishFlavorService dishFlavorService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertDish(DishDTO dto) {
        //保存菜品基本信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        //设置创建时间、修改时间、创建人、修改人
        dish.setCreateTime(LocalDateTime.now());
        dish.setUpdateTime(LocalDateTime.now());
        dish.setCreateUser(BaseContext.getCurrentId());
        dish.setUpdateUser(BaseContext.getCurrentId());
        this.save(dish);
        //保存菜品口味
        List<DishFlavor> dishFlavor = dto.getFlavors();
        if (!CollectionUtils.isEmpty(dishFlavor)) {
            dishFlavor.forEach(flavor -> {
                flavor.setDishId(dish.getId());
            });
            return dishMapper.banchInsert(dishFlavor);
        }
        removeCache();
        return 1;
    }


    /**
     * 分页查询菜品列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult pageDish(DishPageQueryDTO dto) {

        // 先从redis中取数据，如果有数据直接返回给前端
        List<String> stringJsonList = redisTemplate.opsForList()
                .range(RedisKeyConstant.DISH_LIST_CACHE, 0, -1);

        List<Dish> dishListCache;
        if (!CollectionUtils.isEmpty(stringJsonList)) {
            dishListCache = stringJsonList.stream()
                    .flatMap(jsonStr -> JSON.parseArray(jsonStr, Dish.class).stream())
                    .collect(Collectors.toList());
            return new PageResult(dishListCache.size(), dishListCache);
        }

        //如果没查到,去数据库查
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<Dish> dishList = dishMapper.page(dto);
        Page pageList = (Page) dishList;

        PageResult pageResult = new PageResult(pageList.getTotal(), pageList.getResult());
        //查到的数据写入redis
        redisTemplate.opsForList()
                .leftPushAll(RedisKeyConstant.DISH_LIST_CACHE, JSON.toJSONString(dishList));

        return pageResult;

    }

    /**
     * 更新菜品
     *
     * @param dto
     */
    @Override
    public void updateDish(DishDTO dto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        //设置创建时间、修改时间、创建人、修改人
        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());
        this.updateById(dish);
        //删除旧口味
        dishFlavorService.lambdaUpdate()
                .eq(DishFlavor::getDishId, dish.getId())
                .remove();
        //保存新口味
        List<DishFlavor> dishFlavor = dto.getFlavors();
        if (!CollectionUtils.isEmpty(dishFlavor)) {
            dishFlavor.forEach(flavor -> {
                flavor.setDishId(dish.getId());
            });
            dishFlavorService.saveOrUpdateBatch(dishFlavor);
        }
        removeCache();
    }


    //清除redis缓存
    public void removeCache() {
        redisTemplate.delete(RedisKeyConstant.DISH_LIST_CACHE);
    }
}
